package com.feng.project.project01.sv.controller;

import com.feng.project.project01.model.CustomerEntity;
import com.feng.project.project01.model.QCustomerEntity;
import com.feng.project.project01.sv.repository.CustomerRepository;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.UUID;

/**
 * @author Administrator
 */
@RequestMapping("/customer")
@RestController
public class CustomerController {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private ValueOperations<String, String> redisTemplate;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("123")
    public String helloWorld(){
        return "helloWorld";
    }

    @GetMapping("setRedis")
    public String setRedis(String key,String value){
        redisTemplate.set(key,value);
        return key + value;
    }

    @GetMapping("getRedis")
    public String getRedis(String key){
        return redisTemplate.get(key);
    }

    @GetMapping("saveCustomer")
    public String saveCustomer(){
        String name = UUID.randomUUID().toString();
        jdbcTemplate.execute("insert into customer(name,age) values('" + name + "',20)");
        return "success";
    }

    @GetMapping("jpaSaveCustomer")
    @Transactional
    public String jpaSaveCustomer(){
        String name = UUID.randomUUID().toString();
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setName(name).setAge(20);
        entityManager.persist(customerEntity);
        return "success";
    }

    @GetMapping
    public List<CustomerEntity> findAllCustomer(){
        QCustomerEntity qCustomerEntity = QCustomerEntity.customerEntity;
        return new JPAQueryFactory(entityManager)
                .select(qCustomerEntity)
                .from(qCustomerEntity).fetch();
    }

    @GetMapping("findAllCustomerByRepositry")
    public List<CustomerEntity> findAllCustomerByRepositry(){
        return customerRepository.findAll();
    }

}
